package com.lantosec.hmrp.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.kit.tree.TreeNodeVo;
import com.lantosec.hmrp.modules.system.entity.SysDictionaries;
import com.lantosec.hmrp.modules.system.mapper.SysDictionariesMapper;
import com.lantosec.hmrp.modules.system.service.ISysDictionariesService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典表 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-02-11
 */
@Service
@Primary
@Log4j2
@SuppressWarnings("all")
@CacheConfig(cacheNames = "SysDictionariesService")
public class SysDictionariesServiceImpl extends ServiceImpl<SysDictionariesMapper, SysDictionaries> implements ISysDictionariesService {
    /**
     * 字典主树
     *
     * @return 字典树
     */
    @Override
    public List<TreeNodeVo> dictionariesTree() {
        return dictionariesTree(null);
    }


    /**
     * 根据指定ID查询对应的字典树
     *
     * @param dsictionariesId 字典ID
     * @return 字典树
     */
    @Override
    public List<TreeNodeVo> dictionariesTree(String dsictionariesId) {
        List<TreeNodeVo> list = dictionariesNodes(dsictionariesId);
        List tree = new ArrayList<TreeNodeVo>();
        if (list != null && list.size() > 0) {
            list.forEach(node -> {
                if (!node.isLeaf()) {
                    List<TreeNodeVo> children = dictionariesTree(node.getKey());
                    node.setChildren(children);
                }
                tree.add(node);
            });
        }
        return tree;
    }

    /**
     * 获得指定Id下的字典树节点，不包含节点下的子节点
     *
     * @param dsictionariesId 字典ID
     * @return 节点列表
     */
    @Override
    public List<TreeNodeVo> dictionariesNodes(String dsictionariesId) {
        List<SysDictionaries> list = listForParentId(dsictionariesId);
        if (list != null && list.size() > 0) {
            List<TreeNodeVo> nodes = new ArrayList<TreeNodeVo>();
            list.forEach(dictionaries -> {
                nodes.add(new TreeNodeVo(dictionaries.getDictionariesId(), dictionaries.getDictionariesShowName(),dictionaries.getDictionariesId()));
            });
            return nodes;
        }
        return new ArrayList<TreeNodeVo>();
    }

    /**
     * 获得指定Id下的字典列表
     *
     * @param dsictionariesId 字典ID
     * @return 字典列表
     */
    @Override
    @Cacheable(key = "#root.methodName + '-'+ #dsictionariesId")
    public List<SysDictionaries> listForParentId(String dsictionariesId) {
        if(StringUtils.isNotEmpty(dsictionariesId)){
            if(dsictionariesId.startsWith("001001",0) && dsictionariesId.length()>9){
                return null;
            }
            return this.list(new QueryWrapper<SysDictionaries>()
                    .eq(SysDictionaries.ColName.parent_id.toString(), dsictionariesId)
                    .orderByAsc(SysDictionaries.ColName.dictionaries_order.toString(), SysDictionaries.ColName.dictionaries_id.name()));
        }else {
            return this.list(new QueryWrapper<SysDictionaries>().isNull(SysDictionaries.ColName.parent_id.toString())
                    .orderByAsc(SysDictionaries.ColName.dictionaries_order.toString(), SysDictionaries.ColName.dictionaries_id.name()));
        }
    }

    /**
     * 更新字典数据排序
     * @param id
     * @param dictionariesOrder
     */
    @Override
    public void updateOrder(String id, Integer dictionariesOrder) {
        SysDictionaries sysDictionaries = new SysDictionaries();
        sysDictionaries.setDictionariesOrder(dictionariesOrder);
        baseMapper.update(sysDictionaries,new QueryWrapper<SysDictionaries>()
                .eq(SysDictionaries.ColName.dictionaries_id.toString(),id));
    }

    /**
     * 根据数据字典id查询（id为空时查询所有）
     * @param page
     * @param id
     * @return
     */
    @Override
    public List<SysDictionaries> getDictionariesById(String id) {
        if(StringUtils.isNotEmpty(id)){
            return this.list(new QueryWrapper<SysDictionaries>().eq(SysDictionaries.ColName.parent_id.toString(),id)
                    .orderByAsc(SysDictionaries.ColName.dictionaries_order.toString()));
        }else{
            return this.list(new QueryWrapper<SysDictionaries>().isNull(SysDictionaries.ColName.parent_id.toString())
                        .orderByAsc(SysDictionaries.ColName.dictionaries_order.toString()));
        }
    }

    @Override
    public List<TreeNodeVo> getTree(String id){
        List<SysDictionaries> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(id)){
            if(id.startsWith("001001",0) && id.length()>9){
                return null;
            }
            //查出所有的字典树
            list = baseMapper.selectList(new QueryWrapper<SysDictionaries>().eq(SysDictionaries.ColName.parent_id.toString(),id));

        }else{

            list = baseMapper.selectList(new QueryWrapper<SysDictionaries>().isNull(SysDictionaries.ColName.parent_id.toString()));
        }
        List<TreeNodeVo> nodes = new ArrayList<TreeNodeVo>();
        //判断父类为空的
        for(int i=0;i<list.size();i++){
            String parentId = list.get(i).getDictionariesId();
            if(null != parentId){
                //用父类节点为空的id赋值给父id去查子节点
                List<TreeNodeVo> list1 = getTree(parentId);
                nodes.add(new TreeNodeVo(list.get(i).getDictionariesId(),list.get(i).getDictionariesShowName(),list1));
            }
        }
        return nodes;
    }

    /**
     * 通过数据字典名称查询是否有同名的数据名称存在
     * @param dictionariesName
     * @return
     */
    @Override
    public List getDictionariesByName(String dictionariesName){
        return baseMapper.selectList(new QueryWrapper<SysDictionaries>()
                .eq(SysDictionaries.ColName.dictionaries_name.toString(),dictionariesName));
    }

    /**
     * 更新当前名字存在的数据
     * @param entity
     */
    @Override
    public void updateDictionariesByName(SysDictionaries entity){
        String dictionariesName = entity.getDictionariesName();
        baseMapper.update(entity,new QueryWrapper<SysDictionaries>()
                .eq(SysDictionaries.ColName.dictionaries_name.toString(),dictionariesName));
    }


    @Override
    public String queryMaxId(String parentId) {
        String dictionariesId = null;
        if(StringUtils.isNotEmpty(parentId)){
            dictionariesId = baseMapper.queryMaxIdByParentId(parentId);
            return StringUtils.isEmpty(dictionariesId) ? parentId + "001" : dictionariesId;
        }else {
            dictionariesId = baseMapper.queryMaxId();
            return StringUtils.isEmpty(dictionariesId)? "001" : dictionariesId;
        }
    }
}
